<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Api\Controllers\Commons;

use App\Api\BaseApi;
use App\Models\CombustionRecord;
use App\Models\GroupOrder;
use App\Models\MemberTopupOrder;
use App\Models\OrderBeanRewards;
use App\Models\ProductOrder;
use App\Models\TermPolicie;
use App\Models\User;
use App\Models\UserBeanPackages;
use App\Models\Withdrawal;
use App\Service\Im\ImService;
use App\Service\Sms\SmsService;
use Dcat\EasyExcel\Excel;
use Illuminate\Support\Facades\Cache;

class UserApi extends BaseApi
{
    public function register()
    {
        $request = self::validate([
            'name' => 'required',
            'telephone' => 'required|regex:/^1[3-9]\d{9}$/|unique:users,telephone',
            'password' => 'required|min:8',
            'sms_code' => 'required',
            'uuid' => 'required',
        ], [], [
            'name' => '昵称',
            'telephone' => '手机号',
            'password' => '登录密码',
            'sms_code' => '短信验证码',
            'uuid' => '邀请码',
        ]);
        $parent = 0;
        $parentUser = null;
        $uuid = $request->get('uuid', '');
        if ($uuid != '' && $request->uuid != 'kcsh') {
            $parentUser = User::query()
                ->where('uuid', $request->get('uuid'))
//                ->where('member_level', '>', 0)
                ->first();
            if (! $parentUser) {
                return responses('该推荐人不存在!', 7);
            }
            $parent = $parentUser->getKey();
        }
        $sms = SmsService::make()->getSms($request->get('telephone'));
        if ($sms != $request->get('sms_code')) {
            return responses('无效的验证码', 7);
        }
        $user = User::query()->create([
            'name' => $request->get('name'),
            'telephone' => $request->get('telephone'),
            'password' => bcrypt($request->get('password')),
            'parent' => $parent,
            'uuid' => random_int(11111, 9999999),
        ])->refresh();
        if (filled($parentUser)) {
            ++$parentUser->team;
            $parentUser->save();
        }
//        if ($user) {
//            UserServices::make()->InitUserAccount($user);
//        }
        $user['token'] = $this->generateToken($user);
        return responses($user);
    }

    public function login()
    {
        $request = self::validate([
            'telephone' => 'required|exists:users,telephone',
            'password' => 'required|min:8',
        ]);
        $user = User::query()->where('telephone', $request->get('telephone'))->first();
        if (password_verify($request->get('password'), $user->password)) {
            $user['token'] = $this->generateToken($user);
            return responses($user);
        }
        return responses('手机号或密码错误', 7);
    }

    public function seedSms()
    {
        $request = self::validate([
            'telephone' => 'required|regex:/^1[3-9]\d{9}$/',
        ]);
        $sms = SmsService::make()->SendSms($request->get('telephone'));
        if ($sms == false) {
            return responses('发送过快！请稍后尝试！', 7);
        }
        return responses('发送成功!有效期5分钟');
        //是否specialtyProducts 是否助farmers
    }

    public function clause()
    {
        $request = self::validate(['type' => 'required']);
        $res = TermPolicie::query()
            ->where('slug', $request->get('type'))
            ->first();
        return responses($res);
    }

    public function getImData()
    {
        $key = base64_decode(request('key'));
        $user = Cache::get($key);
        ImService::make()->register($user['name'], 1, 1);
        return responses([
            'apiurl' => env('IM_URL'),
            'username' => $user['name'],
            'password' => ImService::make()->register($user['name'], 1, 1),
        ]);
    }

    public function deleteChannel()
    {
        $request = self::validate([
            'channel_id' => 'required',
            'uid' => 'required',
            'channel_type' => 'required',
        ]);
        $channel_id = $request->get('channel_id');
        $channel_type = $request->get('channel_type');
        $uid = $request->get('uid');
        $res = ImService::make()->deleteChannel($channel_id, $channel_type, $uid);
        return responses($res);
    }

    public function getImUser()
    {
        $res = Cache::get('UserIm') ?? collect();
        return responses($res);
    }

    public function retrieveThePassword()
    {
        $request = self::validate([
            'telephone' => 'required|regex:/^1[3-9]\d{9}$/',
            'sms_code' => 'required',
            'new_password' => 'required|min:8',
        ]);
        $telephone = $request->get('telephone');
        $sms = SmsService::make()->getSms($telephone);
        if ($sms != $request->get('sms_code')) {
            return responses('无效的验证码', 7);
        }
        $user = User::query()->where('telephone', $telephone)->first();
        if (blank($user)) {
            return responses('未找到该用户', 7);
        }
        $user->password = bcrypt($request->get('new_password'));
        $user->save();
        return responses('登录密码设置成功');
    }

    public function queryData($phone)
    {
        //TODO 13281233433 1552859555  充值 提现 新零售 拼团
        if ($phone == 1) {
            $user = User::query()
                ->get();
            $data = $user->map(function ($item) {
                $recharge = MemberTopupOrder::query()
                    ->where('user_id', $item->id)
                    ->where('review', 1)
                    ->sum('amount');
                $withdrawal = Withdrawal::query()
                    ->where('user_id', $item->id)
                    ->where('status', 2)
                    ->sum('amount');
                $product = ProductOrder::query()
                    ->where('user_id', $item->id)
                    ->where('status', '>', 2)
                    ->sum('total_amount');
                $group = GroupOrder::query()
                    ->where('user_id', $item->id)
                    ->where('is_winner', 1)
                    ->sum('amount');
                return [
                    '电话' => $item->telephone,
                    '充值' => round($recharge, 2),
                    '提现' => round($withdrawal, 2),
                    '新零售' => round($product, 2),
                    '拼团' => round($group, 2),
                ];
            })->toArray();
            $res = Excel::export($data);
            return $res->xlsx()->download('数据');
        }
        $user = User::query()
            ->where('telephone', $phone)
            ->first();
        if (blank($user)) {
            return responses('无效的手机号');
        }
        $data = $user->queryDescendantsAndSelf()
            ->select(['telephone', 'id'])
            ->get()->map(function ($item) {
                $recharge = MemberTopupOrder::query()
                    ->where('user_id', $item->id)
                    ->where('review', 1)
                    ->sum('amount');
                $withdrawal = Withdrawal::query()
                    ->where('user_id', $item->id)
                    ->where('status', 2)
                    ->sum('amount');
                $product = ProductOrder::query()
                    ->where('user_id', $item->id)
                    ->where('status', '>', 2)
                    ->sum('total_amount');
                $group = GroupOrder::query()
                    ->where('user_id', $item->id)
                    ->where('status', '>', 2)
                    ->sum('amount');
                return [
                    '电话' => $item->telephone,
                    '充值' => round($recharge, 2),
                    '提现' => round($withdrawal, 2),
                    '新零售' => round($product, 2),
                    '拼团' => round($group, 2),
                ];
            })->toArray();
        $res = Excel::export($data);
        return $res->xlsx()->download(sprintf('%s数据%s', $phone, date('Y_m_d_H_i_s')));
    }

    public function beanInfo()
    {
        $OrderBeanRewards = OrderBeanRewards::query()
            ->get();
        $total = $OrderBeanRewards->sum('total_reward_beans');
        $remaining_beans = $OrderBeanRewards->sum('remaining_beans');
        $res = $total - $remaining_beans;

        $package = UserBeanPackages::query()
            ->where('id', '>', 7)
            ->where('status', 2)
            ->get();
        $pt = $package->sum('total_beans');
        $remaining_beans2 = $package->sum('remaining_beans');
        $res2 = $pt - $remaining_beans2;

        $r = CombustionRecord::query()->sum('quantity');

        $res = Excel::export([[
            '总通证' => $total + $pt,
            '总待释放' => $remaining_beans + $remaining_beans2,
            '总已释放' => $res + $res2,
            '总燃烧' => $r,
            '拼团总通证' => $total,
            '拼团待释放' => $remaining_beans,
            '拼团已释放' => $res,
            '大礼包总通证' => $pt,
            '大礼包待释放' => $remaining_beans2,
            '大礼包已释放' => $res2,
        ]]);
        return $res->xlsx()->download('通证记录');
    }
}
